#include "screencapture.h"
#include <QApplication>
#include <QScreen>
#include <QDebug>
#include <QHostAddress>

ScreenCapture::ScreenCapture(QObject *parent) : QObject(parent),
    udpSocket(nullptr), captureTimer(nullptr), isSharingFlag(false),
    captureInterval(200), imageQuality(50), maxSize(800, 600), frameCounter(0)
{
}

ScreenCapture::~ScreenCapture()
{
    if (isSharingFlag) {
        stopSharing();
    }
    
    if (udpSocket) {
        udpSocket->deleteLater();
    }
}

bool ScreenCapture::initialize()
{
    udpSocket = new QUdpSocket(this);
    connect(udpSocket, &QUdpSocket::errorOccurred, this, &ScreenCapture::onSocketError);
    
    captureTimer = new QTimer(this);
    connect(captureTimer, &QTimer::timeout, this, &ScreenCapture::captureAndSend);
    
    qDebug() << "屏幕捕获模块初始化完成";
    return true;
}

void ScreenCapture::startSharing(const QString& teacherIP, int port)
{
    if (isSharingFlag) {
        return;
    }
    
    targetIP = teacherIP;
    targetPort = port;
    
    qDebug() << "开始屏幕共享到:" << targetIP << ":" << targetPort;
    
    isSharingFlag = true;
    frameCounter = 0;
    
    // 立即开始第一次捕获
    captureAndSend();
    
    // 启动定时器
    captureTimer->start(captureInterval);
    
    emit sharingStarted();
}

void ScreenCapture::stopSharing()
{
    if (!isSharingFlag) {
        return;
    }
    
    qDebug() << "停止屏幕共享";
    
    captureTimer->stop();
    isSharingFlag = false;
    
    emit sharingStopped();
}

bool ScreenCapture::isSharing() const
{
    return isSharingFlag;
}

void ScreenCapture::setCaptureInterval(int msecs)
{
    captureInterval = msecs;
    if (captureTimer && captureTimer->isActive()) {
        captureTimer->setInterval(captureInterval);
    }
}

void ScreenCapture::setImageQuality(int quality)
{
    imageQuality = qBound(1, quality, 100);
}

void ScreenCapture::setMaxSize(const QSize& size)
{
    maxSize = size;
}

void ScreenCapture::captureAndSend()
{
    if (!isSharingFlag) {
        return;
    }
    
    try {
        // 1. 捕获屏幕
        QScreen *screen = QApplication::primaryScreen();
        QPixmap screenshot = screen->grabWindow(0);
        
        // 2. 调整尺寸
        if (screenshot.size().width() > maxSize.width() || 
            screenshot.size().height() > maxSize.height()) {
            screenshot = screenshot.scaled(maxSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
        }
        
        // 3. 压缩图像
        QByteArray compressedData = compressImage(screenshot);
        
        // 4. 发送数据
        sendImageData(compressedData);
        
        frameCounter++;
        if (frameCounter % 25 == 0) { // 每25帧打印一次状态
            qDebug() << "屏幕共享: 已发送" << frameCounter << "帧";
        }
        
    } catch (const std::exception& e) {
        emit errorOccurred(QString("屏幕捕获错误: %1").arg(e.what()));
    }
}

QByteArray ScreenCapture::compressImage(const QPixmap& pixmap)
{
    QByteArray imageData;
    QBuffer buffer(&imageData);
    buffer.open(QIODevice::WriteOnly);
    
    // 使用JPEG格式压缩
    pixmap.save(&buffer, "JPEG", imageQuality);
    
    return imageData;
}

void ScreenCapture::sendImageData(const QByteArray& data)
{
    if (!udpSocket) {
        return;
    }
    
    // 发送图像数据
    qint64 bytesSent = udpSocket->writeDatagram(data, QHostAddress(targetIP), targetPort);
    
    if (bytesSent != data.size()) {
        emit errorOccurred("图像数据发送失败");
    }
}

void ScreenCapture::onSocketError(QAbstractSocket::SocketError error)
{
    QString errorStr = QString("UDP Socket错误: %1").arg(udpSocket->errorString());
    emit errorOccurred(errorStr);
}
